<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 500px;
            height: 500px;
            border: 10px solid #000;
            margin: 30px auto;
            position: relative;
        }

        .a {
            width: 100px;
            height: 100px;
            background-color: #f00;
            position: absolute;
            cursor: move;

            /* display: none; */

            opacity: 0;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="a"></div>
    </div>

    <script>

        // display:none 不占位置   -----  浏览器不会渲染这个标签的内部 (样式，，尺寸，内容等)

        // 因此隐藏元素  opacity:0




        var oBox = document.querySelector('.box');



        var oA = oBox.querySelector('.a');

        var r = oA.offsetWidth / 2;;
        console.log(r);

        var bd = parseInt(getComputedStyle(oBox).borderWidth);
        console.log(bd);

        var boxLeft = oBox.offsetLeft;
        var boxTop = oBox.offsetTop;

        var maxLeft = oBox.clientWidth - oA.offsetWidth;
        var maxTop = oBox.clientHeight - oA.offsetHeight;

        // 给大盒子绑定事件
        oBox.onmousemove = function (e) {
            var x = e.x - r - boxLeft - bd;
            var y = e.y - r - boxTop - bd;

            if (x < 0) x = 0;
            if (y < 0) y = 0;
            if (x > maxLeft) x = maxLeft;
            if (y > maxTop) y = maxTop;
            oA.style.left = x + 'px';
            oA.style.top = y + 'px';
        }


        oBox.onmouseout = function () {
            oA.style.opacity = '0';
        }

        oBox.onmouseover = function () {
            oA.style.opacity = '1';
        }


    </script>


</body>

</html>